package com.xmindguoguo.boot.core.aop;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.xmindguoguo.boot.config.properties.ConfigurationKit;
import com.xmindguoguo.boot.core.log.LogManager;
import com.xmindguoguo.boot.core.log.factory.LogModelFactory;
import com.xmindguoguo.boot.core.log.factory.LogTaskFactory;
import com.xmindguoguo.boot.modular.system.model.TSystemOperationLogModel;
import com.xmindguoguo.boot.util.http.HttpUtil;
import com.xmindguoguo.boot.util.json.JsonResult;

import lombok.extern.slf4j.Slf4j;

/**
 * aop操作日志记录
 * 
 * @ClassName OperationLogAop
 * @author <a href="892042158@qq.com" target="_blank">于国帅</a>
 * @date 2019年2月3日 下午9:31:51
 *
 */
@Aspect
@Component
@Slf4j
public class OperationLogAop {

    @Pointcut(value = "@annotation(com.xmindguoguo.boot.common.annotation.OperationLog)")
    public void cutOperationLogService() {
    }

    @Around("cutOperationLogService()")
    public Object recordSysLog(ProceedingJoinPoint point) throws Throwable {
        // 判断是否为演示模式
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        boolean isDemo = ConfigurationKit.CONFIG.getBoolean("isDemo", true);
        if (isDemo) {
            if (HttpUtil.isAjax(request)) { // NoPermissionException
                return JsonResult.sendError("演示模式不允许对数据做出改动");
            } else {
                return "/common/error/demo";
            }
        }
        // 先执行任务逻辑
        long start = System.currentTimeMillis();
        Object result = point.proceed();
        long end = System.currentTimeMillis();
        // 然后记录日志
        TSystemOperationLogModel model = LogModelFactory.getTSystemOperationLogModel(point, result, end - start);
        LogManager.me().executeLog(LogTaskFactory.operationLog(model));
        return result;
    }

}
